<script setup>
    import { onMounted, reactive, ref } from 'vue';
    import { RouterLink } from 'vue-router'
    import { useRouter } from 'vue-router'
    import { ElMessage } from 'element-plus';
    import { handleLogin as LoginApi } from '../api/Login'
    //粒子背景插件
    import { options } from './config/particles-config'

    // 验证码图片URL
    const captchaUrl = ref('/api/login/captcha');

    // 更新验证码的函数
    function updateCaptcha() {
        // 假设您的后端提供了一个接口来获取新的验证码图片
        // 这里使用一个简单的时间戳来模拟动态更新的URL
        captchaUrl.value = `/api/login/captcha?t=${new Date().getTime()}`;
    }

    // 定时更新验证码
    setInterval(updateCaptcha, 300000); // 每5分钟更新一次验证码
    
    const loginForm = ref({
        name: '',
        password: '',
        captcha: ''
    });

    const rules = {
        name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        captcha: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
        ],
    }
    
    const router  = useRouter()

    const handleLogin = async () => {
        try {
            // 触发表单验证
            // const isValid = await $refs.validate();
            // if (!isValid) return;

            const response = await LoginApi(loginForm.value);
            console.log("loginForm.value: ", loginForm.value);
            console.log("用户登录的response: ", response);
            if (response.data.data.isDeleted === 1) {
                ElMessage.error("用户名或密码错误")
                updateCaptcha();    // 更新验证码
            }else if(response.data.data.roleType === "1") {
                // 清除旧的 token
                localStorage.removeItem('token');

                // 获取用户其他基本信息，用于用户名及头像展示
                // 并为后续个人信息界面做准备
                console.log(loginForm.value.name)
                console.log("==> 获取登录用户的信息response.data: ",response);

                // 创建自定义 token，包含
                const userToken = btoa(encodeURIComponent(JSON.stringify({
                    username: loginForm.value.name, // 用户名
                    roleType: response.data.data.roleType,  // 角色权限
                    avatarUrl: response.data.data.avatarUrl,    //头像
                    birthday: response.data.data.birthday,  // 出生日期
                    introduce: response.data.data.introduce,    // 简介
                    sex: response.data.data.sex,    // 性别
                    phone: response.data.data.phone,    // 电话号码
                    email: response.data.data.roleEmail,    // 邮箱
                })));
                // 保存自定义 token
                localStorage.setItem('token', userToken);

                ElMessage.success(`欢迎您! 管理员: ${loginForm.value.name}`)
                //跳转到home页面
                router.push("/home")
            } else if(response.data.data.roleType === "0") {
                ElMessage.success(`欢迎您! ${loginForm.value.name}`)

                // 清除旧的 token
                localStorage.removeItem('token');
                
                // 创建自定义 token，包含用户名
                const userToken = btoa(JSON.stringify({
                    username: loginForm.value.name,
                    // 可以在这里添加其他字段，例如 avatarUrl 等
                }));
                // 保存自定义 token
                localStorage.setItem('token', userToken);

                //跳转到home页面
                router.push("/home")
            } else {
                ElMessage.error(response.data.data)
                updateCaptcha();    // 更新验证码
            }
        } catch (error) {
            console.log("error: ", error);
            ElMessage.error("登录失败!")
            updateCaptcha();    // 更新验证码
        }
    }

    onMounted(() => {
        console.log('===> Login.vue中的onMounted()方法执行了');

        // 初始化验证码
        updateCaptcha();

        // 检查用户是否已经登录
        /*
        const token = localStorage.getItem('token');
        if (token) {
            // 如果已经登录，跳转到首页
            router.push("/home")
        }
            */
    })

</script>

<template>
    <div class="login-container">
        <!-- 粒子背景插件 -->
        <Particles id="tsparticles" class="login-background" :options="options" />

        <el-card class="login-card">

            <h1 class="login-title">登录</h1>

            <div class="login-form">

                <el-form :model="loginForm" :rules="rules" @submit.prevent="handleLogin">

                    <el-row>
                        <el-col :span="24">
                            <el-form-item prop="name">
                                <el-input v-model="loginForm.name" autocomplete="off" prefix-icon="user" maxlength="10" show-word-limit placeholder="请输入用户名"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-form-item prop="password">
                                <el-input type="password" v-model="loginForm.password" autocomplete="off" prefix-icon="lock" maxlength="20" show-password placeholder="请输入密码"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="16">
                            <el-form-item prop="captcha">
                                <el-input v-model="loginForm.captcha" autocomplete="off" prefix-icon="check" maxlength="4" placeholder="请输入验证码"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <!-- 绑定点击事件来更新验证码图片 -->
                            <img :src="captchaUrl" @click="updateCaptcha" class="captcha-image" alt="验证码">
                        </el-col>
                    </el-row>

                    <!--
                    <el-row>
                        <el-form-item class="flex">
                            <div class="flex">
                                <el-checkbox>记住我</el-checkbox>
                                <el-link type="primary" :underline="false">忘记密码？</el-link>
                            </div>
                        </el-form-item>
                    </el-row>
                    -->

                    <el-row>
                        <el-form-item style="width: 100%;">
                            <el-button type="primary" @click="handleLogin" style="width: 100%;">登录</el-button>
                        </el-form-item>
                    </el-row>

                    <!-- 无帐号，点此注册 -->
                    <el-row>
                        <el-text >
                            <RouterLink to="/register">注册-></RouterLink>
                        </el-text>
                    </el-row>
                    
                </el-form>
                <RouterView />
            </div>

        
        </el-card>
    </div>

</template>

<style scoped>
    .login-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    }
    
    .login-card {
        width: 350px;
        padding: 20px;
        background-color: #cde3fba3;
    }
    .login-title {
        text-align: center;
        margin-bottom: 20px;
        color: #105faf;
    }
    .login-form {
        width: 100%;
    }

    .captcha-image {
        cursor: pointer; /* 当鼠标悬停时显示为可点击状态 */
        margin-left: 10px; /* 与输入框保持一定间距 */
        height: 36px; /* 控制图片高度，根据实际情况调整 */
        vertical-align: middle; /* 垂直居中对齐 */
    }

    .login-background {
        height: 100%;
        width: 100%;
        background-size: cover;
        background-repeat: no-repeat;
        /*background-image: url('@/assets/bgImg/login-bg-1.webp');*/
        opacity:0.7;
        position:fixed;
        pointer-events: none;
    }
    .flex {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }
</style>